/**
 * 评分系统
 * @param { number } kpm 按键速度
 * @param { number } accuracy 准确率
 * @param { number } backspaceCount 退格次数
 */
function getScore({ kpm, wpm, accuracy, backspaceCount }) {
	if (accuracy < 10) {
		return 0;
	} else if (accuracy < 60) {
		return 30;
	}

	// 基本参数
	const baseKPM = 165; // 基准KPM
	const baseWPM = 65; //基准WPM
	const maxScore = 100; // 最高分
	const backspacePenalty = 3; // 每次退格的扣分

	// 计算速度评分
	let speedScore = kpm > 0 ? Math.max((kpm / baseKPM) * maxScore, 0) : Math.max((wpm / baseWPM) * maxScore, 0);
	speedScore = speedScore > 100 ? 100 : speedScore;

	// 计算准确率评分
	let accuracyScore = accuracy;
	// 计算退格数评分
	let backspaceScore = -backspaceCount * backspacePenalty;

	// 动态权重调整
	let weightSpeed = 0.5; // 初始速度权重
	let weightAccuracy = 0.5; // 初始准确率权重

	// 根据速度调整准确率权重
	if (speedScore == 100) {
		weightAccuracy = 0.8;
		weightSpeed = 0.2;
	}

	// 确保权重总和为1
	weightSpeed = Math.min(Math.max(weightSpeed, 0), 1);
	weightAccuracy = Math.min(Math.max(weightAccuracy, 0), 1);

	// 计算综合评分
	let compositeScore = (speedScore * weightSpeed + accuracyScore * weightAccuracy + backspaceScore);
	// 四舍五入到小数点后两位
	compositeScore = Math.round(compositeScore * 100) / 100;
	// 确保评分不会超过100分
	compositeScore = Math.min(compositeScore, maxScore);

	return Math.round(compositeScore);
}
/**
 * 根据分数获取星级1-5
 * @param {Object} score 评分
 */
function getStar(score) {
	const starList = [
		{ star: 0, limit: [0, 10] },
		{ star: 1, limit: [11, 40] },
		{ star: 2, limit: [41, 65] },
		{ star: 3, limit: [66, 80] },
		{ star: 4, limit: [81, 95] },
		{ star: 5, limit: [96, 100] }
	]
	let star = 0;
	starList.forEach(item => {
		if (score >= item.limit[0] && score <= item.limit[1]) {
			star = item.star;
		}
	})
	return star;
}
/**
 * 根据星级获取积分
 * @param {Object} star 星级
 */
function getIntegral(star) {
	const integralList = [
		{ star: 0, integral: 0 },
		{ star: 1, integral: 20 },
		{ star: 2, integral: 40 },
		{ star: 3, integral: 60 },
		{ star: 4, integral: 80 },
		{ star: 5, integral: 100 }
	]
	let integral = 0;
	integralList.forEach(item => {
		if (star == item.star) {
			integral = item.integral;
		}
	})
	return integral;
}
/**
 * 评分系统
 * @param { number } kpm 按键速度
 * @param { number } accuracy 准确率
 * @param { number } backspaceCount 退格次数
 */
module.exports = ({ kpm, wpm, accuracy, backspaceCount } = {}) => {
	const score = getScore({ kpm, wpm, accuracy, backspaceCount });
	const star = getStar(score);
	const integral = getIntegral(star);
	return {
		score,
		star,
		integral
	}
}